import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import 'rxjs/add/operator/toPromise';

import { UserService } from "../../providers/UserService";
import { StorageService } from "../../providers/StorageService";

import { HomePage } from '../home/home';
import { RegisterPage } from '../register/register';
import { ForgotPasswordPage } from '../forgotPassword/forgotPassword';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [UserService]
})
export class LoginPage {
  local: Storage;
  constructor(
    public navCtrl: NavController,
    private formBuilder: FormBuilder,
    public toastCtrl: ToastController,
    private userService: UserService,
    private storageService: StorageService
  ) {
    localStorage.clear();
  }

  loginForm = this.formBuilder.group({
    'user_account': ['', [Validators.required]],
    'user_password': ['', [Validators.required]]
  });

  login(user, _event) {
    _event.preventDefault();
    this.userService.login(user).then(data => {
      if (data.status == 200)//登录成功
      {
        this.storageService.write('UserInfo', data.user);
        this.navCtrl.push(HomePage, { user_id: data.user.user_id });

        localStorage.setItem('user_token', data.user.user_token);
      }
      else {
        let toast = this.toastCtrl.create({
          message: '用户名或密码错误.',
          duration: 3000,
          position: 'top',
          showCloseButton: true,
          closeButtonText: '关闭'
        });
        toast.present();
      }
    })
  }

  registerUser() {
    this.navCtrl.push(RegisterPage);
  }

  forgotPassword() {
    this.navCtrl.push(ForgotPasswordPage);
  }
}
